<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      label-width="100px"
      label-position="left"
    >
      <h1 class="title" style="font-size: 50px; margin-bottom: 10px">鸽物</h1>
      <h1 class="title">工厂管理系统</h1>

      <el-form-item prop="username" label="账号">
        <el-input v-model="loginForm.username" placeholder="请输入">
          <svg-icon
            slot="prefix"
            icon-class="user"
            class="el-input__icon input-icon"
          />
          <</el-input
        >
      </el-form-item>

      <el-form-item prop="code" label="短信验证码">
        <el-input v-model="loginForm.code">
          <template slot="append">
            <span @click="countdownChange">{{ countdown.validText }}</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item style="width: 100%; margin-top: 50px">
        <el-button
          type="primary"
          @click="submitForm('loginForm')"
          style="width: 80%"
          >登录</el-button
        >
      </el-form-item>
      <!-- <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width: 100%"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item> -->
    </el-form>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";

export default {
  name: "Login",
  data() {
    // 账号校验规则
    const validateUser = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        const phoneReg =
          /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
        phoneReg.test(value)
          ? callback()
          : callback(new Error("手机号格式不对，请输入正确手机号"));
      }
    };
    return {
      flag: false,
      countdown: {
        validText: "获取验证码",
        times: 60,
      },
      codeUrl: "",
      loginForm: {
        username: "13461523526",
        code: "",
      },

      loginRules: {
        username: [
          { required: true, validator: validateUser, trigger: "blur" },

          // { required: true, trigger: "blur", message: "请输入您的账号" },
        ],

        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
    };
  },

  watch: {
    // $route: {
    //   handler: function (route) {
    //     this.redirect = route.query && route.query.redirect;
    //   },
    //   immediate: true,
    // },
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    countdownChange() {
      if (this.flag) return;
      // 手机号正则
      const phoneReg =
        /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
      if (!this.loginForm.username || !phoneReg.test(this.loginForm.username)) {
        return this.$message({
          message: "手机号格式不正常，请输入正确手机号",
          type: "warning",
        });
      }
      const time = setInterval(() => {
        if (this.countdown.times <= 0) {
          this.countdown.times = 60;
          this.countdown.validText = `获取验证码`;
          this.flag = false;
          clearInterval(time);
        } else {
          this.countdown.validText = `剩余${this.countdown.times}s`;
          this.countdown.times -= 1;
        }
      }, 1000);
      this.flag = true;
    },
    async submitForm(val) {
      await this.$refs["loginForm"].validate();

      this.$router.push("/index");

      //  this.$refs[loginForm].validateField()
    },
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" }).catch(() => {});
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
@import "./index.scss";
</style>
